<template>
  <TwoDialog v-model="visible" id="WriteDialog" icon="fontisto:email" :title="formatEmailTypeText" width="910px" bodyClass="bodyClass" @close="closeDialog">
    <template #header>
      <span>{{ formatEmailTypeText }}</span>
      <span class="ml10">{{ currentTime }}</span>
    </template>

    <OneContextMenu :items="contextMenuItems" @click.right="getSelectedText">
      <el-upload class="upload-attachment" :http-request="customUpload">
        <div ref="uploadRef"></div>
      </el-upload>
      <div class="forms">
        <el-form :model="form" label-width="86px">
          <el-form-item label="收件人：">
            <div class="flex recipient-container">
              <div class="recipient-input-wrapper">
                <!-- Replace existing el-select with our custom component -->
                <RecipientSelector v-model="form.recipients" :placeholder="'请输入收件人邮箱'" :contacts="recipList"
                  @focus="handleEmailInputFocus('recipient')" @blur="handleSelectBlur" />
              </div>
              <el-button class="action-btn" :class="ccAddressVis ? 'active' : ''" @click="ccAddressVis = !ccAddressVis"
                size="small">抄送</el-button>
              <el-button class="action-btn" :class="bccAddressVis ? 'active' : ''" @click="bccAddressVis = !bccAddressVis"
                size="small">密送</el-button>
            </div>
          </el-form-item>
          <div class="border"></div>
          <el-form-item label="抄送人：" v-if="ccAddressVis">
            <recipients v-model="form.ccAddress" placeholder="请输入抄送人邮箱" />
          </el-form-item>
          <div v-if="ccAddressVis" class="border"></div>
          <el-form-item label="密送人：" v-if="bccAddressVis">
            <el-select v-model="form.bccAddress" multiple filterable allow-create size="samll" :reserve-keyword="false"
              placeholder="请输入密送人邮箱" />
          </el-form-item>
          <div v-if="bccAddressVis" class="border"></div>
          <el-form-item label="主题：">
            <el-input v-model="form.subject" placeholder="请输入主题" />
          </el-form-item>
        </el-form>
      </div>
      <el-form-item class="ai_item" label="AI生成回复">
        <el-input v-model="aiContent" placeholder="请输入">
          <template #append>
            <el-button v-loading="aiLoading" element-loading-svg-view-box="0, 0, 1024, 1024"
              :element-loading-svg="LoadingSvg" @click="handlerAi" class="input_btn" type="primary"
              size="small">生成</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item class="ai_item" label="AI翻译">
        <el-input v-model="translateContent" placeholder="请输入">
          <template #append>
            <el-button v-loading="translateLoading" @click="handlerTranslate" class="input_btn" type="primary"
              size="small">翻译</el-button>
          </template>
        </el-input>
      </el-form-item>
      <div class="htmls">
        <SummerNote id="writeEmailSummerNote" :height="400" v-model="editorContent" :isEmail="true" @useTemplate="handlerShowTemplate"
          @addAttach="handlerAddFile" />
        <div class="template_list" v-if="templateVisable">
          <div class="template_item" :key="temp.id" @click="handleCommand(temp.content)" v-for="temp in templateList">
            {{ temp.title }}
          </div>
        </div>
      </div>
      <div v-if="form.attachmentNames.length" class="attachment-wrap">
        <div @click="previewFile(item)" class="attachment-item-wrap" v-for="(item, index) in form.attachmentNames"
          :key="index">
          <i class="iconfont icon-file" />
          <span class="file-name">{{ item.fileName }}</span>
          <span class="file-size">( {{ formatSize(item.fileSize) }} )</span>
        </div>
      </div>
    </OneContextMenu>
    <template #footer>
      <div class="footer">
        <el-select class="account_select" placeholder="Select" v-model="form.from" @change="changeAccount">
          <el-option v-for="item in accountList" :key="item.id" :label="item.account" :value="item.account" />
        </el-select>
        <div>
          <el-button v-loading="saving" element-loading-svg-view-box="0, 0, 1024, 1024" :element-loading-svg="LoadingSvg"
            @click="onClick({ value: 'save' })" class="save_btn" type="primary" plain>保存</el-button>
          <el-button v-loading="saving" element-loading-svg-view-box="0, 0, 1024, 1024" :element-loading-svg="LoadingSvg"
            @click="onClick({ value: 'send' })" class="save_btn" type="primary">发送</el-button>
        </div>
      </div>
    </template>
    <!-- 翻译 -->
    <TranslateView ref="translateViewRef" />
  </TwoDialog>
</template>

<script lang="ts" setup>
import dayjs from 'dayjs';
import { ElMessage, ElMessageBox } from 'element-plus';
import { storeToRefs } from 'pinia';
import { getEmailName } from '/@/utils/index';
import { useTempCache } from '/@/stores/tempCache';
// import { useRoute } from 'vue-router';
const TranslateView = defineAsyncComponent(() => import('./translateView.vue'));

import { useEmail } from '/@/stores/email';
import pinia from '/@/stores/index';

import api from '/@/api/email/index';
import commonApi from '/@/api/common/index';
import { downloadRemoteFile } from '/@/utils/webView';
import { customUploadMultiple } from '/@/utils/upload';
import { LoadingSvg } from '/@/utils/loading';

import SummerNote from '/@/components/summerNote/index.vue';
import recipients from './recipients.vue';

import RecipientSelector from './recipientSelector.vue';

const props = defineProps({
  currentMessageId: {
    type: [String, Number],
    default: ''
  },
})

const translateViewRef = ref()
// 引入组件
const tempCache = useTempCache(pinia);
const emailType = ref('');
const emailId = ref('');
const messageId = ref('');
const recipSelectRef = ref();
const recipList = ref<any[]>([]);
const minimized = ref(false);
const visible = ref(false);
const uploadRef = ref();
const templateVisable = ref(false);
const aiLoading = ref(false);
const translateLoading = ref(false);
const translateContent = ref('');
const saving = ref(false);
const formatEmailTypeText = ref('');
const selectedTextForReply = ref("");
// const route = useRoute()
// const appendToBody = computed(() => route.path !== '/home')

// 抄送 密送显示
const ccAddressVis = ref(false);
const bccAddressVis = ref(false);

const currentTime = ref('');
const aiContent = ref('');

const handlerAddFile = () => {
  uploadRef.value.click();
};

const handlerShowTemplate = () => {
  setTimeout(() => {
    templateVisable.value = true;
  }, 0);
};

const stores = useEmail(pinia);
const { sign, curAccount, accountList } = storeToRefs(stores);
// const curSign = ref(sign.value);
const curSign = ref('');

const editorContent = ref('');

const emailInfo = ref();
const templateList = ref<any>([]);

const form = ref<any>({
  attachmentNames: [],
  bccAddress: [],
  ccAddress: [],
  content: '',
  from: curAccount.value,
  recipients: [],
  subject: ''
});

const emit = defineEmits(['closeDialog']);

const formatEmailType = (type: string) => {
  if (type === 'forward') {
    return '转发邮件';
  }
  if (type === 'replyAll') {
    return '回复全部';
  }

  if (type === 'reply') {
    return '回复';
  }

  if (type === 'writeEmail') {
    return '写邮件';
  }
}

const handleCommand = (content: string) => {
  templateVisable.value = false;
  editorContent.value = getInitContent(content);
};

const formatSize = (kb: number) => {
  if (kb <= 0) {
    return "0 B";
  }

  const units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  const i = Math.floor(Math.log(kb) / Math.log(1024));
  return (kb / Math.pow(1024, i)).toFixed(2) + " " + units[i];
}

const onReplySelected = (payload: any) => {
  console.log('onReplySelected payload:', payload);
  
  if (!payload) {
    console.error('payload is undefined');
    return;
  }
  
  const { selectedText, emailData } = payload;
  
  if (!emailData) {
    console.error('emailData is undefined');
    return;
  }
  
  if (!emailData.id || !emailData.messageId) {
    console.error('emailData missing required fields:', emailData);
    return;
  }
  
  selectedTextForReply.value = selectedText;
  messageId.value = emailData.messageId;
  open('reply', emailData.id, emailData.messageId, selectedText);
};
// 获取选中的内容
const getSelectedText = () => {
  const selection = window.getSelection();
  if (selection && selection.rangeCount > 0) {
    const selectedText = selection.toString();
    selectText.value = selectedText
  } else {
    selectText.value = ''
  }
}
// 选中的文本
const selectText = ref('')
const contextMenuItems = ref([{
    id: 'translate',
    label: '翻译',
    show: computed(() => !!selectText.value),
    action: (obj: any) => {
      const { event } = obj
      translateViewRef.value.translate({
          position: { left: event.clientX, top: event.clientY },
          data: selectText.value
      })
    }
  }, {
    id: 'reply_selected',
    label: '回复',
    show: computed(() => !!selectText.value),
    action: () => {
      onReplySelected({
          selectedText: selectText.value,
          emailData: {
            id: stores.currentId,
            messageId: props.currentMessageId
          }
      })
    }
  }
])

const resetFormVal = () => {
  form.value = {
    attachmentNames: [],
    bccAddress: [],
    ccAddress: [],
    content: '',
    from: curAccount.value,
    recipients: [],
    subject: ''
  }
}

const customUpload = async (e: any) => {
  const { file } = e;
  const res = await customUploadMultiple([file]);
  console.log(res)
  const { url } = res[0];
  form.value.attachmentNames.push({
    fileName: file.name,
    fileUrl: url,
    fileSize: file.size
  });
}

const previewFile = (file: any) => {
  // 下载文件
  downloadRemoteFile(file.fileUrl, file.fileName);
};

const closeDialog = () => {
  editorContent.value = ""
  form.value.content = '';
  visible.value = false;
  minimized.value = false;
  setTimeout(() => {
    emit('closeDialog');
  }, 300); // 等待动画完成再关闭
};


// 处理邮箱输入框获得焦点事件
const handleEmailInputFocus = (type: string) => {
  // 这里可以处理不同类型输入框的焦点事件
  // type: 'recipient', 'cc', 'bcc'
  console.log(`${type} input focused`);

  // 可以在此处理加载最近联系人等操作
  if (recipList.value.length === 0) {
    // 异步加载最近联系人
    setTimeout(() => {
      // 这里可以调用API加载联系人列表
      // 示例仅为演示
      const recentContacts = getRecentContacts();
      if (recentContacts.length > 0) {
        recipList.value = [...recentContacts];
      }
    }, 100);
  }
};

// 获取最近联系人列表（示例函数，实际可连接到API）
const getRecentContacts = () => {
  // 这里应该调用API获取最近联系人
  // 这是一个示例实现
  const savedContacts = localStorage.getItem('recentContacts');
  if (savedContacts) {
    try {
      console.log(JSON.parse(savedContacts))
      return JSON.parse(savedContacts);
    } catch (e) {
      console.error('Failed to parse recent contacts', e);
    }
  }
  return [];
};

// 接收表单提交事件
const onClick = (menu: any) => {
  if (!form.value.recipients.length) {
    return ElMessage.error('请输入收件人');
  }
  if (!form.value.subject) {
    const content = menu.value === 'send' ? '仍然发送' : '仍然保存';
    ElMessageBox.confirm(
      '该邮件没有主题，仍然要发送吗？',
      '邮件没有主题',
      {
        confirmButtonText: content,
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(() => {
        operateEmail(menu)
      })
      .catch(() => {
        console.log(form)
        ElMessage({
          type: 'info',
          message: '操作已取消',
        });
      })
  } else {
    operateEmail(menu);
  }
};

const operateEmail = (menu: any) => {
  if (menu.value === 'send') {
    if (emailId.value) {
      // 回复邮件
      replyEmail();
    } else {
      sendMail();
    }
  } else if (menu.value === 'save') {
    saveDraft();
  }
}
/**
 * 回复邮件
 */
const replyEmail = () => {
  api.email.sendMail({
    // 回复邮件id
    messageId: emailType.value !== 'forward' ? messageId.value : "",
    // 收件人
    recipients: form.value.recipients.join(','),
    // 	邮件附件 
    attachmentNames: form.value.attachmentNames,
    // 密送人
    bccAddress: form.value.bccAddress?.join(','),
    // 抄送人
    ccAddress: form.value.ccAddress?.join(','),
    // 回复内容
    content: editorContent.value,
    // 发件人
    from: form.value.from,
    // 主题
    subject: form.value.subject
  }).then(() => {
    ElMessage.success('保存成功');
    close();
  })
}

// 切换账号 切换签名
const changeAccount = async (account: string) => {
  if (curAccount.value === account) {
    curSign.value = sign.value;
    editorContent.value = getInitContent('');
  } else {
    const res = await api.email.getSign(account);
    if (res.code === 200) {
      curSign.value = res.data || '';
      editorContent.value = getInitContent('');
    }
  }
};

const saveDraft = () => {
  saving.value = true;
  api.email.saveDraft({
    from: form.value.from,
    recipients: form.value.recipients.join(','),
    subject: form.value.subject,
    "attachmentNames": form.value.attachmentNames,
    "bccAddress": form.value.bccAddress.join(','),
    "ccAddress": form.value.ccAddress.join(','),
    "content": editorContent.value,
  }).then(() => {
    ElMessage.success('保存成功');
    saving.value = false;
    close();
  })
}

const sendMail = () => {
  saving.value = true;
  api.email.sendMail({
    from: form.value.from,
    recipients: form.value.recipients.join(','),
    subject: form.value.subject,
    "attachmentNames": form.value.attachmentNames,
    "bccAddress": form.value.bccAddress.join(','),
    "ccAddress": form.value.ccAddress.join(','),
    "content": editorContent.value,
  }).then((res: any) => {
    saving.value = false;
    if (res.data) {
      ElMessage.success('发送成功');
      close();
    } else {
      ElMessage.success('发送失败，请稍后再试');
    }
  })
}

const formatCurrenTime = () => {
  currentTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss');
}

const removeFirstAndLastCharSlice = (str: string) => {
  if (str.length <= 1) {
    return str; // 如果字符串长度不大于1，则直接返回原字符串
  }

  if (str.startsWith('<')) {
    return str.slice(1, str.length - 1); // 去掉第一个和最后一个字符
  }

  return str;
}

setInterval(formatCurrenTime, 1000);
const close = () => {
  editorContent.value = "";
  form.value.content = '';
  visible.value = false;
  minimized.value = false;
  setTimeout(() => {
    emit('closeDialog');
  }, 300); // 等待动画完成再关闭
};

const getInitContent = (aiContent: string) => {
  let str = `<div><br></div>`;
  // 无邮件 直接返回签名
  if (!emailId.value) {
    return aiContent + str + curSign.value + str;
  }
  console.log("curSign.value:", curSign.value)
  console.log("emailId.value:", emailId.value)
  // 有邮件的情况-回复/转发
  // let info1 =`<span>---- Replied Message ----</span>`;
  let info1 = `<div style="margin:2em 0 1em;font-size:14px;line-height:1.25;color:#78787a">---- Replied Message ----</div>`

  if (emailType.value === 'forward') {
    // info1 = '<span>---- Forwarded Message ----</span>';
    info1 = `<div style="margin:2em 0 1em;font-size:14px;line-height:1.25;color:#78787a">---- Forwarded Message ----</div>`
  }
  // ccEmail 抄送人
  let ccEmail = emailInfo.value.ccEmail ? `
  <tr>
    <td valign="top" style="width:4.25em;font-size:12px;line-height:1.25;color:#78787a">Cc</td>
    <td class="" valign="top" style="font-size:12px;line-height:1.25;color:#232324;word-break:break-all">
      <a class="mail-to" style="color:#3061f2;text-decoration:none" href="mailto:${emailInfo.value.ccEmail}">${emailInfo.value.ccEmail}&lt;${emailInfo.value.ccEmail}&gt;</a>
    </td>
  </tr>` : '';
  // fromEmailName 发件人名称
  let fromEmailName = emailInfo.value.fromEmailName;
  // fromEmail 发件人邮箱
  let fromEmail = removeFirstAndLastCharSlice(emailInfo.value.fromEmail);
  let table = `
     <table width="100%" cellpadding="0" cellspacing="9" border="0" id="ntes_editor_table_10010" class="ntes_editor_table ntes_editor_ext_table ">
      <tbody>
        <tr>
          <td valign="top" style="width:4.25em;font-size:12px;line-height:1.25;color:#78787a">From</td>
          <td class="" valign="top" style="font-size:12px;line-height:1.25;color:#232324;word-break:break-all">
            <a class="mail-from" style="color:#3061f2;text-decoration:none"
              href="mailto:undefined">${fromEmailName}&lt;${fromEmail}&gt;</a>
          </td>
        </tr>
        <tr>
          <td valign="top" style="width:4.25em;font-size:12px;line-height:1.25;color:#78787a">Sent</td>
          <td class="mail-date" valign="top"
            style="font-size:12px;line-height:1.25;color:#232324;word-break:break-all">${dayjs(emailInfo.value.sentDate).locale('en').format('MMMM Do YYYY, h:mm:ss A')}</td>
        </tr>

        <tr>
          <td valign="top" style="width:4.25em;font-size:12px;line-height:1.25;color:#78787a">To</td>
          <td class="" valign="top" style="font-size:12px;line-height:1.25;color:#232324;word-break:break-all">
            <a class="mail-to" style="color:#3061f2;text-decoration:none" href="mailto:${emailInfo.value.toEmail}">${emailInfo.value.toEmail}&lt;${emailInfo.value.toEmail}&gt;</a>
          </td>
        </tr>
        ${ccEmail}
        <tr>
          <td valign="top" style="width:4.25em;font-size:12px;line-height:1.25;color:#78787a">Subject</td>
          <td class="" valign="top" style="font-size:12px;line-height:1.25;color:#232324;word-break:break-all">${emailInfo.value.subject}</td>
        </tr>
      </tbody>
     </table>    
  `;
  // info 信息
  let info = `${info1}<div style="margin-bottom:1em;font-size:12px;line-height:1.25;color:#232324;padding:0.5em 0.25em;border-radius:0.67em;background-color:#f0f0f0">${table}</div>`;
  // str3 邮件内容
  let str3 = emailInfo.value.bodyText;
  let body = '<div class="J-reply ntes-mailmaster-quote" style="padding-top: 1px; padding-bottom: 1px; font-family: &quot;PingFang SC&quot;;">' + info + str3 + '</div>';
  console.log("body-body-body:", str + (aiContent || '') + str + curSign.value + str + body)
  return str + (aiContent || '') + str + curSign.value + str + body;
}

const getInfo = async (id: string) => {
  const list = Promise.all([api.email.getDetail(id), api.email.getBody(id)]);
  const res = await list;
  const info = {
    ...(res[0].data[0] || {}),
    bodyText: res[1].data
  };
  return info;
};

const getDetail = () => {
  getInfo(emailId.value).then((info: any) => {
    emailInfo.value = info;
    if (emailType.value === 'forward') {
      console.log("emailInfo.value:", emailInfo.value)
      // 转发
      // 转发情况下让收件人自动获取焦点
      if (recipSelectRef.value && recipSelectRef.value.inputRef && recipSelectRef.value.inputRef.focus) {
        recipSelectRef.value.inputRef.focus();
      }
      // 副标题 添加Fw：
      if (emailInfo.value.subject.startsWith('Fw:')) {
        form.value.subject = emailInfo.value.subject;
      } else {
        form.value.subject = 'Fw:' + emailInfo.value.subject;
      }

    } else {
      // 回复标题加Re:
      if (emailInfo.value.subject.startsWith('Re:')) {
        form.value.subject = emailInfo.value.subject;
      } else {
        form.value.subject = 'Re:' + emailInfo.value.subject;
      }

      if (emailType.value === 'replyAll') {
        // 回复全部
        if (emailInfo.value.ccEmail) {
          form.value.recipients = emailInfo.value.fromEmail.split(',').concat(emailInfo.value.ccEmail.split(',')).filter((item: any) => item !== curAccount.value)
        } else {
          form.value.recipients = emailInfo.value.fromEmail.split(',');
        }
        if (emailInfo.value.toEmail) {
          form.value.recipients = form.value.recipients.concat(emailInfo.value.toEmail.split(','));
        }
        // 删除form.value.recipients中值为form.value.from值的数据
        form.value.recipients = form.value.recipients.filter((item: any) => {
          return item !== form.value.from;
        });
      } else {
        // 回复
        form.value.recipients = emailInfo.value.fromEmail?.split(',');
      }
    }

    // 处理收件人 显示： 邮件名+邮箱
    if (form.value.recipients.length) {
      const list = form.value.recipients.map((str: string) => {

        console.log(str)
        console.log("name:", getEmailName(str))
        let name = getEmailName(str) + '<' + str + '>';
        if (str === emailInfo.value.fromEmail) {
          if (emailInfo.value.fromEmailName) {
            name = emailInfo.value.fromEmailName + '<' + str + '>';
          }
        }

        return {
          id: str,
          name
        };
      });

      recipList.value = list;
    }
    // 发件人 当前账号
    form.value.from = curAccount.value;
    editorContent.value = getInitContent('');
  });
}

const handlerAi = async () => {
  if (!aiContent.value) {
    ElMessage.warning('请输入内容');
    return;
  }

  if (aiLoading.value) {
    return;
  }

  aiLoading.value = true;

  let res;
  try {
    if (emailId.value) {

      // 检查是否有选中内容用于回复
      const requestParams = {
        id: emailId.value,
        input: aiContent.value
      };

      // 如果有选中内容，添加到请求参数中
      if (selectedTextForReply.value) {
        requestParams.input = selectedTextForReply.value;
      }

      res = await api.email.emailWrite(requestParams);
      aiLoading.value = false;
    } else {
      res = await api.email.expression(aiContent.value);
      aiLoading.value = false;
      if (res.data.code === false) {
        ElMessage.warning(res.data.msg);
        return;
      }
    }
  } catch (error) {
    aiLoading.value = false;
    return;
  }

  handlerAiSuccess(res.data);
};

const handlerTranslate = async () => {
  if (!translateContent.value) {
    ElMessage.warning('请输入内容');
    return;
  }

  if (translateLoading.value) {
    return;
  }

  translateLoading.value = true;

  let res;
  try {
    res = await commonApi.translate(translateContent.value);
    translateLoading.value = false;
    if (res.data.code === false) {
      ElMessage.warning(res.data.msg);
      return;
    }
  } catch (error) {
    translateLoading.value = false;
    return;
  }

  editorContent.value = res.data.translated + '\r\n' + editorContent.value;
};

// 调用ai成功后
const handlerAiSuccess = (data: any) => {
  let replayCon = '';
  if (emailId.value) {
    replayCon = data.data || '';
  } else {
    // 新建
    form.value.subject = data.subject;
    replayCon = data.content || '';
  }
  replayCon = replayCon.replace(/\n/g, '<br/>');
  editorContent.value = getInitContent(replayCon);
};

const getTemplateList = async () => {
  const res = await api.template.getList({});
  if (res.code === 200) {
    templateList.value = res.data;
  }
};

const editingRecipientIndex = ref(-1);
let tagClickInterval = null;

onMounted(() => {
  // 给整个document添加点击事件代理
  document.addEventListener('click', handleGlobalClick);

  // 开始轮询检查标签元素并附加特殊类标识
  startTagsMonitoring();
});

onBeforeUnmount(() => {
  // 清理全局事件监听
  document.removeEventListener('click', handleGlobalClick);

  // 停止轮询
  if (tagClickInterval) {
    clearInterval(tagClickInterval);
    tagClickInterval = null;
  }
});

// 全局点击事件处理
const handleGlobalClick = (event) => {
  // 查找被点击的元素是否在我们感兴趣的区域内
  const target = event.target;

  // 查找是否点击了带有特殊标记的标签
  if (target &&
    (target.classList.contains('recipient-tag-text') ||
      target.closest('.recipient-tag-text'))) {

    event.stopPropagation();
    event.preventDefault();

    // 获取标签文本
    const tagText = target.textContent.trim();
    console.log('捕获到标签点击:', tagText);

    // 找到对应的收件人索引
    const index = form.value.recipients.findIndex(recipient =>
      recipient === tagText || recipient.toString() === tagText);

    if (index !== -1) {
      handleRecipientEdit(index, tagText);
      return false;
    }
  }
};

// 开始监控标签
const startTagsMonitoring = () => {
  // 先执行一次
  markTags();

  // 每300ms检查一次标签，为新标签添加标识类
  tagClickInterval = setInterval(markTags, 300);
};

// 为标签添加特殊标记
const markTags = () => {
  // 找到所有收件人标签
  const tags = document.querySelectorAll('.recipient-container .el-tag');

  tags.forEach(tag => {
    const textEl = tag.querySelector('.el-select__tags-text');
    if (textEl && !textEl.classList.contains('recipient-tag-text')) {
      // 添加我们的特殊标记类
      textEl.classList.add('recipient-tag-text');
      console.log('添加标记到标签:', textEl.textContent.trim());
    }
  });
};

// 处理收件人编辑
const handleRecipientEdit = (index, tagText) => {
  console.log('处理收件人编辑:', index, tagText);

  // 如果已经在编辑其他收件人，先取消之前的编辑
  if (editingRecipientIndex.value !== -1 && editingRecipientIndex.value !== index) {
    cancelRecipientEditing();
  }

  // 设置为当前编辑的收件人索引
  editingRecipientIndex.value = index;

  // 给当前编辑的标签添加样式
  nextTick(() => {
    const tagTextElements = document.querySelectorAll('.recipient-container .recipient-tag-text');

    // 移除所有编辑中样式
    tagTextElements.forEach(el => el.classList.remove('editing-recipient'));

    // 查找并添加样式到当前编辑的标签
    tagTextElements.forEach((el) => {
      if (el.textContent.trim() === tagText) {
        el.classList.add('editing-recipient');
      }
    });

    // 设置输入框值并聚焦
    if (recipSelectRef.value) {
      recipSelectRef.value.query = tagText;
      recipSelectRef.value.focus();
      recipSelectRef.value.visible = true;
    }
  });
};

// 取消编辑
const cancelRecipientEditing = () => {
  if (editingRecipientIndex.value !== -1) {
    // 移除编辑样式
    const tagTextElements = document.querySelectorAll('.recipient-container .recipient-tag-text');
    tagTextElements.forEach(el => el.classList.remove('editing-recipient'));

    // 清空输入框
    if (recipSelectRef.value) {
      recipSelectRef.value.query = '';
    }

    // 重置索引
    editingRecipientIndex.value = -1;
  }
};

// 处理输入框失焦
const handleSelectBlur = () => {
  // 添加延时，防止与点击事件冲突
  setTimeout(() => {
    if (editingRecipientIndex.value !== -1) {
      cancelRecipientEditing();
    }
  }, 200);
};

const open = (type: string, emailIdValue: string, messageIdValue: string, selectedTextForReplyValue: string) => {
  // console.log('emailType:', type)
  // console.log('emailIdValue:', emailIdValue)
  // console.log('messageIdValue:', messageIdValue)
  // console.log('open:', form.value)
  resetFormVal();
  emailType.value = type;
  emailId.value = emailIdValue || '';
  messageId.value = messageIdValue || '';
  curSign.value = sign.value;
  // console.log("sign.value2:", sign.value)
  if (emailId.value) {
    getDetail();
    // 如果有选中文本，自动触发AI生成
    if (selectedTextForReplyValue && selectedTextForReplyValue.trim()) {
      // 延迟执行，确保组件完全加载后再触发AI
      setTimeout(() => {
        aiContent.value = selectedTextForReplyValue;
        handlerAi();
      }, 500);
    }
  }
  getTemplateList();
  if (type == 'writeEmail') {
    const data: any = tempCache.getData();
    // console.log("data:", data)
    let str = `<div><br></div>`;
    editorContent.value = data?.content ? data.content + str + sign.value + str : str + sign.value + str;
    form.value = {
      attachmentNames: [],
      bccAddress: [],
      ccAddress: [],
      content: '',
      from: curAccount.value,
      recipients: data ? [data.toEmail] : [],
      subject: data ? data.title : ''
    };
    if (data) {
      recipList.value = [{
        id: data ? data.toEmail : '',
        name: `${data ? data.toEmailName : ''} <${data ? data.toEmail : ''}>`
      }];
    }
  }

  formatEmailTypeText.value = formatEmailType(type) || '-----';
  visible.value = true;
  minimized.value = false;

}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.forms {
  padding: 6px 13px 8px 0;
  border-top: 1px solid #e7e7e7;
  border-bottom: 1px solid #e7e7e7;

  :deep(.el-form-item) {
    margin-bottom: 0;
  }

  :deep(.el-form-item + .el-form-item) {
    margin-top: 8px;
  }

  :deep(.el-input__wrapper) {
    box-shadow: none;
    background-color: #f5f6f7;
  }

  :deep(.el-select__wrapper) {
    box-shadow: none;
    background-color: #f5f6f7;
    height: 26px;
    line-height: 26px;
    padding: 1px 15px;
  }

  :deep(.el-input__inner) {
    height: 26px;
    line-height: 26px;
  }
}

.htmls {
  display: flex;
  flex: 1;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

:deep(.el-upload-list) {
  display: none;
}

.upload-attachment {
  display: none;
}

.attachment-wrap {
  display: flex;
  flex-wrap: wrap;
  background: #fff;
  height: 10vh;
  padding: 10px;
  cursor: auto;

  .attachment-item-wrap {
    margin-right: 20px;
    height: 18px;
    line-height: 18px;
    display: flex;
    justify-content: center;
    align-items: center;

    .file-size {
      color: var(--el-text-color-regular);
    }

    .file-name {
      color: #293c4f;
    }
  }

  .attachment-item-wrap:hover {
    text-decoration: underline;
    cursor: pointer;
    color: #293c4f;
  }

  i {
    font-size: 12px;
  }

  .icon-file {
    font-size: 12px;
    margin: 0 5px;
    color: #fca146;
  }
}

.flex {
  display: flex;
  width: 100%;
  align-items: center;

  .auto {
    flex: 1;
  }
}

.small_btn {
  margin-left: 20px;
  border: none;

  &.active {
    background-color: #D8E9FE;
    color: #3B7AEE;
  }
}

.hand {
  position: absolute;
  top: 4px;
  right: 6px;
  font-size: 20px;
}

.ml10 {
  margin-left: 10px;
}

.border {
  border-bottom: 1px solid #ddd;
  margin-top: 5px;
  margin-bottom: 10px;
  margin-left: 20px
}

.el-dropdown-link {
  font-size: 12px;
  padding-top: 5px;
}

.footer {
  text-align: right;
  padding: 12px 20px;
  border-top: 1px solid #e7e7e7;
  justify-content: space-between;
  display: flex;
}

.account_select {
  width: 230px;
}

.save_btn {
  width: 100px;
}

.template_list {
  position: absolute;
  z-index: 10;
  left: 5px;
  top: 45px;
  background-color: #fff;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);

  .template_item {
    padding: 7px;
    width: 120px;
    cursor: pointer;

    &:hover {
      background-color: #eee;
    }
  }
}

.ai_item {
  margin: 10px;
  background-color: #fff;
  padding: 12px 10px;

  :deep(.el-loading-spinner) {
    --el-loading-spinner-size: 20px;
    color: #3B7AEE;
  }

  :deep(.el-input__wrapper) {
    box-shadow: none;
  }

  :deep(.el-input-group__append) {
    box-shadow: none;
    background-color: #fff;
  }

  .input_btn {
    background-color: #3B7AEE;
    color: #fff;
    border: none;

    &:hover {
      color: #fff;
      background-color: #79bbff;
    }
  }
}

.icon-full {
  font-size: 13px;
  margin-right: 5px;
}

.icon-recover {
  font-size: 14px;
  margin-right: 5px;
}

.iconfont {
  color: #000;
}

.floating-icon {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 50px;
  height: 50px;
  background-color: #409EFF;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  cursor: pointer;
  z-index: 2000;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;

  &:hover {
    transform: scale(1.1);

    .float-text {
      opacity: 1;
      transform: translateX(-110%);
    }
  }

  i {
    font-size: 24px;
  }

  .float-text {
    position: absolute;
    left: 0;
    background: #409EFF;
    padding: 5px 10px;
    border-radius: 4px;
    white-space: nowrap;
    opacity: 0;
    transform: translateX(-90%);
    transition: all 0.3s ease;
  }
}

// 动画效果
.dialog-minimize {
  animation: dialogMinimize 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  transform-origin: right bottom;
}

.dialog-maximize {
  animation: dialogMaximize 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28);
  transform-origin: right bottom;
}

@keyframes dialogMinimize {
  from {
    opacity: 1;
    transform: scale(1);
  }

  to {
    opacity: 0;
    transform: scale(0.2);
    transform-origin: right bottom;
  }
}

@keyframes dialogMaximize {
  from {
    opacity: 0;
    transform: scale(0.2);
    transform-origin: right bottom;
  }

  to {
    opacity: 1;
    transform: scale(1);
  }
}

.float-transition-enter-active,
.float-transition-leave-active {
  transition: all 0.3s ease;
}

.float-transition-enter-from,
.float-transition-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

.recipient-container {
  position: relative;
  width: 100%;
}

.recipient-input-wrapper {
  flex: 1;
  position: relative;
}

.recipient-select {
  width: 100%;

  :deep(.el-select__tags) {
    background-color: transparent;
    padding-left: 5px; // 修改为统一的padding
    display: flex;
    flex-wrap: wrap;
  }

  &.has-recipients {
    :deep(.el-select__tags) {
      padding-left: 5px;
    }
  }

  :deep(.el-select__wrapper) {
    background-color: white;
    border-radius: 4px;
    padding: 2px 4px;
    min-height: 36px;

    &:hover {
      border-color: #409EFF;
    }
  }

  // 移除为收标签预留的padding
  :deep(.el-input__inner) {
    padding-left: inherit;
  }

  :deep(.el-select__tags-text) {
    max-width: none;
    display: inline-block;
  }

  :deep(.el-tag) {
    background-color: #f0f7ff;
    border-color: #d0e6ff;
    color: #409EFF;
    margin: 2px;
    border-radius: 12px;
    max-width: none;

    .el-tag__close {
      background-color: #d0e6ff;
      color: #409EFF;

      &:hover {
        background-color: #409EFF;
        color: white;
      }
    }
  }
}

.recipient-option {
  display: flex;
  flex-direction: column;
  padding: 4px 0;
}

.recipient-name {
  font-weight: bold;
  font-size: 14px;
}

.recipient-email {
  font-size: 12px;
  color: #909399;
}

.action-btn {
  margin-left: 8px;
  border-radius: 4px;

  &.active {
    color: #409EFF;
    border-color: #409EFF;
  }
}

.no-data {
  padding: 8px 0;
  text-align: center;

  .hint {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
  }
}

/* 编辑中的收件人样式 */
:deep(.editing-recipient) {
  color: #409EFF;
  font-weight: bold;
  text-decoration: underline;
  background-color: rgba(64, 158, 255, 0.1);
  padding: 0 4px;
  border-radius: 3px;
}

/* 添加标签悬停样式，提示可编辑 */
:deep(.el-select__tags-text) {
  cursor: pointer;

  &:hover {
    text-decoration: underline;
    color: #409EFF;
  }
}

/* 修改提示文本 */
.recipient-container .el-select__tags:hover::after {
  content: '点击修改';
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 12px;
  opacity: 0.6;
}
</style>
<style lang="scss">
.bodyClass {
  padding: 0px !important;
  background: #F5F6F7;
}
</style>